<template>
  <el-dropdown>
        <span class="el-dropdown-link">
          <div class="demo-basic--circle">
            <div class="block">
              <el-avatar :size="50" :src="userAvatarUrl"/>
            </div>
          </div>
        </span>
    <template #dropdown>

      <el-dropdown-menu class="dropdown-menu-style">
        <!-- 头像模块 -->
        <div>
          <el-avatar @click="dialogVisible = true" :size="50" :src="userAvatarUrl"
                     style="scale: 1.5;margin-block: 20px;cursor: pointer;"/>
          <el-dialog
              v-model="dialogVisible"
              title="上传头像"
              width="500"
              :before-close="handleClose"
          >

            <el-upload
                class="upload-demo"
                drag
                action="#"
                :http-request="uploadAvatar"
                multiple
                :show-file-list="false"
            >
              <el-icon class="el-icon--upload">
                <upload-filled/>
              </el-icon>
              <div class="el-upload__text">
                <em>点击</em>或拖动图片至此处
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  图片大小不超过2MB
                </div>
              </template>
            </el-upload>

            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
              </div>
            </template>
          </el-dialog>
        </div>

        <h3 style="margin-top: 5px"> 仙豆：{{ userBeanInfo.balance }}</h3>
        <h2>段位：{{ userExpInfo.levelName }}</h2>
        <div style="display:flex;justify-content: center;align-items: center;">
          <img src="@/assets/svg/exp-16.svg" style="margin-right: 20px;margin-left: 16px"/>
          <el-progress :percentage="expPercentage"
                       style="width: 300px" :stroke-width="12" striped>
            <span></span>
          </el-progress>
        </div>
        <span>当前经验值{{
            userExpInfo.experienceValue
          }}, 距离下一个段位需要{{ userExpInfo.threshold - userExpInfo.experienceValue }}经验值</span>
        <div style="margin-top: 20px">
          <el-dropdown-item class="dropdown-item" @click="goToMySpacePage">
            <img src="@/assets/svg/user-16.svg" style="margin-right: 20px"/>
            <span style="font-size: 16px">{{ userinfo.nickname }}</span>
            <img src="@/assets/svg/right-16.svg" style="position: absolute;right: 20px"/>
          </el-dropdown-item>
          <el-dropdown-item @click="goToMySpacePage" class="dropdown-item">
            <img src="@/assets/svg/home-16.svg" style="margin-right: 20px"/>我的空间
            <img src="@/assets/svg/right-16.svg" style="position: absolute;right: 20px"/>
          </el-dropdown-item>
          <el-dropdown-item class="dropdown-item" disabled>
            <img src="@/assets/svg/update-password-16.svg" style="margin-right: 20px"/>修改密码
            <img src="@/assets/svg/right-16.svg" style="position: absolute;right: 20px"/>
          </el-dropdown-item>
          <el-divider style="margin-block: 5px"/>
          <el-dropdown-item @click="logout" class="dropdown-item"><img src="@/assets/svg/logout-16.svg"
                                                                       style="margin-right: 20px"/>退出登录
            <img src="@/assets/svg/right-16.svg" style="position: absolute;right: 20px"/>
          </el-dropdown-item>
        </div>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>

import {ref, getCurrentInstance, onMounted} from "vue";
import {ElMessageBox, ElLoading,ElMessage } from "element-plus";
import {UploadAvatar} from "@/api/member/upload.js";
import {GetBeanByUserId, GetUserExp} from "@/api/member/user.js";
import {useUserinfo} from "@/components/hooks/useUserinfo.js";
import defaultAvatar from '@/assets/avatar/default-avatar.png';
import {Logout} from "@/api/member/login.js";
import {useApp} from "@/pinia/modules/app.js";
import {useRouter} from "vue-router";
import axios from 'axios';


const router = useRouter()
const {userinfo} = useUserinfo()
const {proxy: ctx} = getCurrentInstance() // 可以把ctx当成vue2中的this
let userAvatarUrl = ref(null)


/** 获取头像图片外访URL */
const fetchAvatarUrl = async () => {
  try {
    if (userinfo.value.avatar != null) {
      userAvatarUrl.value = userinfo.value.avatar
      await axios.get(userinfo.value.avatar)
    } else {
      userAvatarUrl.value = defaultAvatar
    }
  } catch (error) {
    // 在网络错误时回退到默认头像URL
    userAvatarUrl.value = defaultAvatar
    ElMessage.warning("头像已失效，已使用默认头像，请根据需要上传新头像！")
  }
}


/**头像更改**/
let dialogVisible = ref(false)
const handleClose = () => {
  ElMessageBox.confirm('确定取消更改头像吗?')
      .then(() => {
        dialogVisible.value = false
      })
      .catch((error) => {
        ctx.$message.error(error)
      })
}


/**头像上传**/
const uploadAvatar = async (data) => {
  const flag = await checkImage(data);
  if (flag) {
    let formData = new FormData();
    formData.append("file", data.file)
    formData.append("userId", userinfo.value.id)
    const {code, msg} = await UploadAvatar(formData)
    try {
      if (code === 200) {
        ctx.$message.success(msg)
        dialogVisible.value = false
      } else {
        ctx.$message.error(msg)
      }
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    } catch (error) {
      ctx.$message.error(error)
    }
  } else {
    ctx.$message.error("图片违规，请更改！")
  }

}


/**图片内容审核**/
const checkImageResponseData = ref([]);
const checkImage = async (data) => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '头像审核中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    let formData = new FormData();
    formData.append("image", data.file);
    // const url = 'http://localhost:8004/nsfw'; // 你的 API URL
    const url = import.meta.env.VITE_NSFW_URL; // 你的 API URL
    const response = await axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 如果你需要明确指定这个头部，但通常 axios 会自动处理
      }
    });
    checkImageResponseData.value = response.data; // 将响应数据存储在响应式引用中
    const className = checkImageResponseData.value[0].className;
    const probability = checkImageResponseData.value[0].probability;
    console.log(className, probability);
    loading.close()
    if (className === "Sexy" || className === "Hentai" || className === "Porn") {
      if (probability > 0.85) {
        return false;
      }
    }
    return true;
  } catch (error) {
    loading.close()
    console.error('Error:', error);
  }
};
/**==========================**/


/** 获取用户仙豆信息 **/
const userBeanInfo = ref([])
const fetchBeanByUserId = async () => {
  const {code, data, msg} = await GetBeanByUserId(userinfo.value.id)
  if (code === 200) {
    userBeanInfo.value = data
  } else {
    ctx.$message.error(msg)
  }
}


/** 获取用户经验信息 **/
const userExpInfo = ref([])
const expPercentage = ref(0)
const fetchUserExp = async () => {
  const {code, data, msg} = await GetUserExp(userinfo.value.id)
  if (code === 200) {
    userExpInfo.value = data
    expPercentage.value = (userExpInfo.value.experienceValue) / (userExpInfo.value.threshold) * 100
    // console.log("userExpInfo", userExpInfo)
  } else {
    ctx.$message.error(msg)
  }
}


/** 退出**/
const logout = async () => {
  const {code, data, msg} = await Logout();
  if (code === 200) {
    // 清除token
    useApp().clearToken()
    router.push('/login')
  } else {
    ctx.$message.error(msg)
  }

}

// 跳转我的空间页面
const goToMySpacePage = () => {
  router.push('/goToMySpacePage')
}

onMounted(() => {
  fetchUserExp();
  fetchBeanByUserId();
  fetchAvatarUrl();
})

</script>

<style scoped>

.block {
  flex: 1;
}

/* 头像*/
.demo-basic--circle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -10px;
}

.dropdown-menu-style {
  width: 300px;
  height: 380px;
  text-align: center;
}

.dropdown-item {
  display: flex;
  justify-content: center;
  align-items: center;
}


</style>